<?php


namespace app\community\oauth2\Model;


use app\cms\community\lib\QueryModel;
use app\cms\model\userModel;

class oauthClientModel extends QueryModel
{
    protected $table = 'oauth_client_table';

    /**
     * 关联用户
     * @return \think\model\relation\HasOneThrough
     */
    public function hasUser(): \think\model\relation\hasManyThrough
    {
        // TODO: 关联用户
        return $this->hasOneThrough(
            userModel::class,
            oauthUserUnionClientModel::class,
            'app_id',
            'uid',
            'app_id',
            'uid'
        );
    }

    /**
     * 获取客户端账户信息
     * @param string $clientId
     * @return array
     */
    public function getClientById(string $clientId): array
    {
        return $this->findInfo([
            'app_id' => $clientId
        ]);
    }

    /**
     * 获取 关联客户端数据
     * @param string $userName
     * @param string $clientId
     * @param string $clientSecret
     * @return array|\think\Model|\think\model\relation\HasManyThrough
     */
    public function getUnionUserInfoByUserName(string $userName, string $clientId, string $clientSecret): array|\think\Model|\think\model\relation\HasManyThrough
    {
        return self::hasWhere('hasUser', [
            'user_table.user_name' => $userName,
            'oauth_client_table.app_id' => $clientId,
        ], joinType: 'LEFT')
        -> field([
            '`user_table`.user_name',
            '`user_table`.uid',
            '`user_table`.password',
            '`user_table`.status',
        ])
        -> findOrEmpty();
    }
}